
package com.joysuch.wwyt.dataimport.controller;

import com.alibaba.fastjson.JSONArray;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.dataimport.bean.CheckItemBean;
import com.joysuch.wwyt.dataimport.service.DataImportService;
import com.joysuch.wwyt.patrol.entity.bean.PatrolCheckPointItemDetailBean;
import com.joysuch.wwyt.util.ZipDownloadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/data/import")
@Api(tags = "/bp/exceldataimport模板导入")
public class ExcelImportController {
    @Autowired
    private DataImportService dataImportService;

    /**
     * 模板下载
     *
     * @param response
     * @throws Exception
     */
    // @RequestMapping("/download")
    @PostMapping(" ")
    @ApiOperation(value = "excel模板下载")
    public void download(HttpServletResponse response, @RequestBody ArrayList<String> name) throws Exception {
        // service.download(response);
        List<String> fileName = new ArrayList<>();
        List<byte[]> fileContent = new ArrayList<>();
        for (int i = 0; i < name.size(); i++) {
            String filename = "模板导入_";
            String current = name.get(i);
            if (current.contains("01")) {
                filename = current + filename + "企业基础信息.xlsx";
            } else if (current.contains("02")) {
                filename = current + filename + "部门导入.xlsx";
            } else if (current.contains("03")) {
                filename = current + filename + "岗位导入.xlsx";
            } else if (current.contains("04")) {
                filename = current + filename + "人员档案.xlsx";
            } else if (current.contains("05")) {
                filename = current + filename + "风险区域_区域固定风险导入.xlsx";
            } else if (current.contains("06")) {
                filename = current + filename + "区域控制风险导入.xlsx";
            } else if (current.contains("07")) {
                filename = current + filename + "危化品导入.xlsx";
            } else if (current.contains("08")) {
                filename = current + filename + "重大危险源导入.xlsx";
            } else if (current.contains("09")) {
                filename = current + filename + "监测点导入.xlsx";
            } else if (current.contains("10")) {
                filename = current + filename + "生产装置导入.xlsx";
            } else if (current.contains("11")) {
                filename = current + filename + "储罐区_储罐导入模板.xlsx";
            } else if (current.contains("12")) {
                filename = current + filename + "工业管道导入.xlsx";
            } else if (current.contains("13")) {
                filename = current + filename + "风险点数据库导入.xlsx";
            }
            InputStream stream = ExcelImportController.class.getClassLoader()
                    .getResourceAsStream("template/" + filename);
            if (stream != null) {
                BufferedInputStream bufin = new BufferedInputStream(stream);
                ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                byte[] temp = new byte[1024];
                int size = 0;
                while ((size = bufin.read(temp)) != -1) {
                    out.write(temp, 0, size);
                }
                bufin.close();
                byte[] content = out.toByteArray();
                fileContent.add(content);
                fileName.add(filename);
            }
        }
        ZipDownloadUtil.downloadZip(response, "temlpates.zip", fileContent, fileName);

    }

    /**
     * 企业基础信息导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:enterpriseBasicInformation")
    @PostMapping("/enterpriseBasicInformation")
    @ApiOperation(value = "企业基础信息导入")
    public ResultBean imporBasicInformationByExcel(MultipartFile file) {
        List<String> list = dataImportService.imporBasicInformationByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * 部门导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:depart")
    @PostMapping("/depart")
    @ApiOperation(value = "部门导入")
    public ResultBean importDepartByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importDepartByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * 岗位导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:job")
    @PostMapping("/job")
    @ApiOperation(value = "岗位导入")
    public ResultBean importJobByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importJobByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * 人员导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:user")
    @PostMapping("/user")
    @ApiOperation(value = "人员导入")
    public ResultBean importUserByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importUserByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * 人员邮箱导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:userEmail")
    @PostMapping("/userEmail")
    @ApiOperation(value = "人员邮箱导入")
    public ResultBean importUserEmailByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importUserEmailByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * 危化品导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:hazardousChemicals")
    @PostMapping("/hazardousChemicals")
    @ApiOperation(value = "危化品导入")
    public ResultBean imporHazardousChemicalsByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.imporHazardousChemicalsByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * 重大危险源导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:dangerouSource")
    @PostMapping("/dangerouSource")
    @ApiOperation(value = "重大危险源导入")
    public ResultBean imporDangerouSourceByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.imporDangerouSourceByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * 设备装置导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:equipmentAndFacilities")
    @PostMapping("/equipmentAndFacilities")
    @ApiOperation(value = "设备装置导入")
    public ResultBean importMonitoringPointByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.equipmentAndFacilities(file);
        return ResultBean.success(list);
    }

    /**
     * 导入储罐、储罐区
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:tankAndArea")
    @PostMapping("/tankAndArea")
    @ApiOperation(value = "储罐和储罐区导入")
    public ResultBean importBpStoreTankAndAreaByExcel(MultipartFile file) {
        List<String> list = dataImportService.importBpStoreTankAndArea(file);
        return ResultBean.success(list);
    }

    /**
     * 工业管道导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:pipe")
    @PostMapping("/pipe")
    @ApiOperation(value = "工业管道导入")
    public ResultBean imporPipeByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importPipeByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * 试题导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:question")
    @PostMapping("/question")
    @ApiOperation(value = "试题导入")
    public ResultBean importQuestionByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importQuestionByExcel(file);
        return ResultBean.success(list);
    }

    /**
     * NFC卡导入
     *
     * @param file
     * @return
     */
    @RequiresPermissions("data:import:nfc")
    @PostMapping("/nfc")
    @ApiOperation(value = "NFC卡导入")
    public ResultBean importNfcByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importNfcByExcel(file);
        return ResultBean.success(list);
}

    @RequiresPermissions("data:import:point")
    @PostMapping("/point")
    @ApiOperation(value = "监测点导入")
    public ResultBean imporPointByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importPointByExcel(file);
        return ResultBean.success(list);
    }

    @RequiresPermissions("data:import:risk-point")
    @PostMapping("/risk-point")
    @ApiOperation(value = "风险点&控制风险导入")
    public ResultBean imporRiskPointByExcel(MultipartFile file) {
        List<String> list = dataImportService.importRiskPointByExcel(file);
        return ResultBean.success(list);
    }

    @RequiresPermissions("data:import:risk-district")
    @PostMapping("/risk-district")
    @ApiOperation(value = "风险区域&固定风险评估导入")
    public ResultBean imporRiskDistrictByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importRiskDistrictStableByExcel(file);
        return ResultBean.success(list);
    }

    @RequiresPermissions("data:import:work-cert-evaluation-templates")
    @PostMapping("/work-cert-evaluation-templates")
    @ApiOperation(value = "风险点库数据导入")
    public ResultBean importWorkSafetyCertRiskPointEvaluationTemplateByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importWorkSafetyCertRiskPointEvaluationTemplateByExcel(file);
        return ResultBean.success(list);
    }

    @RequiresPermissions("data:import:video")
    @PostMapping("/video")
    @ApiOperation(value = "视频设备导入")
    public ResultBean imporVideoByExcel(MultipartFile file) {
        List<String> list = dataImportService.imporVideoByExcel(file);
        return ResultBean.success(list);
    }

    @RequiresPermissions("data:import:riskDistrict")
    @PostMapping("/riskDistrict")
    @ApiOperation(value = "风险区域导入")
    public ResultBean importRiskDistrictByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importRiskDistrictByExcel(file);
        return ResultBean.success(list);
    }

    @RequiresPermissions("data:import:certificate")
    @PostMapping("/certificate")
    @ApiOperation(value = "持证管理导入")
    public ResultBean importCertificateByExcel(MultipartFile file){
        // 获取文件全名
        String filename = file.getOriginalFilename();
        if (!filename.contains(".xlsx")){
            throw new IllegalArgumentException("请使用 .xlsx 格式文件上传");
        }
        List<String> list = dataImportService.importCertificateByExcel(file);
        return ResultBean.success(list);
    }

    @RequiresPermissions("data:import:importCheckItem")
    @PostMapping("/importCheckItem")
    @ApiOperation("检查点下的检查项目导入")
    public ResultBean importCheckItem(@RequestParam(value = "file") MultipartFile file , String frontEndDataJson, Integer flag){
        // flag  0:追加 在前端传给的检查项目集合上加上模板数据一同给前端   1:覆盖   将前端检查项目有id的数据作为delIds给前端,模板数据给前端
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(400, "文件类型不正确");
        }
//        if(!file.getOriginalFilename().contains("检查项目")){
//            return ResultBean.fail(500, "请导入正确的模板");
//        }
        List<PatrolCheckPointItemDetailBean> beanList = new ArrayList<>();
        if (StringUtils.isNotBlank(frontEndDataJson)){
            JSONArray jsonArray = JSONArray.parseArray(frontEndDataJson);
            beanList = jsonArray.toJavaList(PatrolCheckPointItemDetailBean.class);
        }
        CheckItemBean checkItemBean = dataImportService.importCheckItem(file,beanList,flag);
        return ResultBean.success(checkItemBean);
    }

    @RequiresPermissions("data:import:IMEI")
    @PostMapping("/IMEI")
    @ApiOperation(value = "人员导入")
    public ResultBean importIMEIByExcel(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.fail(500, "文件类型不正确");
        }
        List<String> list = dataImportService.importIMEIByExcel(file);
        return ResultBean.success(list);
    }
}